package com.test.getorload;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.pojo.Product;

/**
 * @description load和get方式处理id加载不存的问题
 * @author Leon Plious
 * @date 2020年7月6日
 */
public class HibernateTestGetAndLoadForIdNull {

/*
Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
null
Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.cid as cid0_0_ from product_ product0_ where product0_.id=?
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.pojo.Product#100]	
 */
	public static void main(String[] args) {
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		// get当id不存在返回null
		Product p1 = (Product) session.get(Product.class, 100);
		System.out.println(p1);
		// load当id不存在报错
		Product p2 = (Product) session.load(Product.class, 100);
		System.out.println(p2);
		
		session.getTransaction().commit();
		session.close();
		sessionFactory.close();
	}
}
